//
//  JXHttpRequest.m
//  Demo
//
//  Created by xiu on 2020/4/22.
//  Copyright © 2020 111. All rights reserved.
//

#import "JXHttpRequest.h"
#import "UIDevice+isJail.h"
#import "TokenGenerator.h"
#import "NSObject+MJKeyValue.h"
#import "SocketManager.h"
#import "JXRequestManager+JX.h"

@implementation JXRequestConfig
+ (instancetype)sharedManager {
    static JXRequestConfig *_manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[JXRequestConfig alloc] init];
    });
    
    return _manager;
}
@end

@interface JXHttpRequest() {
    NSLock           *_reLock;       //线程锁
}
@end

@implementation JXHttpRequest

- (NSMutableDictionary *)deviceData {
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    [param setValue:[NSNumber numberWithBool:UIDevice.isSimulator] forKey:@"isSimulator"];
    [param setValue:UIDevice.deviceIMSI forKey:@"imsi"];
    [param setValue:UIDevice.deviceSystemVersion forKey:@"deviceSystemVersion"];
    [param setValue:UIDevice.devicePlatformSystem forKey:@"devicePlatformSystem"];
    [param setValue:UIDevice.idfa forKey:@"idfa"];
    [param setValue:UIDevice.iPhoneName forKey:@"iPhoneName"];
    [param setValue:UIDevice.iPhoneLanguage forKey:@"iPhoneLanguage"];
    [param setValue:UIDevice.mobileNetworkCode forKey:@"networkCode"];
    [param setValue:UIDevice.countryCode forKey:@"countryCode"];
    [param setValue:[NSNumber numberWithBool:UIDevice.isJailBreak1] forKey:@"isJailBreak1"];
    [param setValue:[NSNumber numberWithBool:UIDevice.isJailBreak2] forKey:@"isJailBreak2"];
    return param;
}

//生成新的url
- (NSString *)dicsToUrl:(NSString *)url params:(NSMutableDictionary *)dic
{
    NSString *UUID = [[NSUUID UUID] UUIDString];
    int appid = JXRequestConfig.sharedManager.appId.intValue;
    NSString *platform = @"IOS";
    NSString *appkey = JXRequestConfig.sharedManager.apiKey;
    NSString *ts = [NSString stringWithFormat:@"%lld",(long long int)[[NSDate date] timeIntervalSince1970]];
    if ([dic objectForKey:@"ts"]) ts = [dic objectForKey:@"ts"];
    NSString *token = [TokenGenerator tokenGenerationWith:JXRequestConfig.sharedManager.appVer uuid:UUID appid:[NSString stringWithFormat:@"%d",appid] platform:platform appkey:appkey ts:ts];
    [dic setObject:UUID forKey:@"uuid"];
    [dic setObject:[NSNumber numberWithInteger:appid] forKey:@"app_id"];
    [dic setObject:platform forKey:@"platform"];
    if (![dic objectForKey:@"ts"]) [dic setObject:ts forKey:@"ts"];
    [dic setObject:token forKey:@"token"];
    if (!dic){
        return url;
    }
    NSMutableString *mustr = [[url stringByAppendingString:@"?"] mutableCopy];
    NSArray *dicKeys = [dic allKeys];
    for (NSString *key in dicKeys){
        [mustr appendFormat:@"%@=%@&",key,dic[key]];
    }
    if ([mustr hasSuffix:@"&"]){
        [mustr deleteCharactersInRange:NSMakeRange(mustr.length - 1, 1)];
    }
    return mustr;
}


-(void)netserverts:(NSString *)ts body:(id)body result:(void (^)(BOOL isSuccess,id object))callBack
{
    NSString *url = JXRequestConfig.sharedManager.apiHost;
    NSMutableDictionary *newDic = [[NSMutableDictionary alloc] init];
    [newDic setObject:JXRequestConfig.sharedManager.appVer forKey:@"ver"];
    [newDic setObject:JXRequestConfig.sharedManager.appPackage forKey:@"bundleId"];
    [newDic setObject:@"ios" forKey:@"osType"];
    url = [self dicsToUrl:url params:newDic];
    NSMutableDictionary *postBody = [NSMutableDictionary dictionary];
    if ([body isKindOfClass:[NSDictionary class]]) {
        [postBody addEntriesFromDictionary:body];
        [postBody addEntriesFromDictionary:@{@"device":self.deviceData}];
        body = postBody;
    }

    NSData *badyData = [[TokenGenerator neu_encryptAESData2:[body mj_JSONString]] dataUsingEncoding:NSUTF8StringEncoding];
    
    NetLog(@"网络调用接口 ==%@" ,url);
    weak_block_self;
    NSURLSessionDataTask *operation =
    [JXRequestManager.sharedInstance dataTaskWithPOSTURLString:url
       Body:badyData
    success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *cryptAES = [(NSDictionary *)responseObject objectForKey:@"Enc"];
        NSString *encryptAES = [TokenGenerator neu_decryptAESData:cryptAES];
        NSDictionary *resultObject = [encryptAES mj_JSONObject];
        if (encryptAES && encryptAES.length) {
            if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]){
                LOError *err = [weakSelf checkIsSuccess:resultObject];
                if (!callBack) {
                    return;
                }
                callBack(err==nil?YES:NO,[resultObject objectForKey:@"datas"]);
            } else if (callBack) {
                callBack(NO,MAKE_ERROR(@"数据格式错误", 1000));
            }
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        LOError *loerror = MAKE_ERROR(error.localizedFailureReason, error.code);
        if (callBack){
            callBack(NO,loerror);
        }
    }];
    
    [operation resume];
}

- (void)netBody:(id)body result:(void (^)(BOOL isSuccess,id object))callBack
{
    [self netserverts:nil body:body result:callBack];
}

- (void)requestServerTimeResult:(void (^)(BOOL isSuccess,id object))callBack
{
    NSDictionary *body = @{@"class":@"search",
                           @"method":@"ts",
                           @"msgid":@(1),@"params":@{}};
    NSString *url = JXRequestConfig.sharedManager.apiHost;
    NSMutableDictionary *newDic = [[NSMutableDictionary alloc] init];
    [newDic setObject:JXRequestConfig.sharedManager.appVer forKey:@"ver"];
    [newDic setObject:JXRequestConfig.sharedManager.appPackage forKey:@"bundleId"];
    [newDic setObject:@"ios" forKey:@"osType"];
    url = [self dicsToUrl:url params:newDic];
    NetLog(@"网络调用接口 ==%@" ,url);
    
    NSData *badyData = [[body mj_JSONString] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *operation =
    [JXRequestManager.sharedInstance dataTaskWithPOSTURLString:url
                                         Body:badyData
                                      success:^(NSURLSessionDataTask *task, id responseObject) {
                                          if (responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
                                              NSDictionary *dic = (NSDictionary *)responseObject;
                                              if ([dic objectForKey:@"datas"]) {
                                                  id datas = [dic objectForKey:@"datas"];
                                                  if ([datas isKindOfClass:[NSArray class]] &&
                                                      ((NSArray *)datas).count > 0 ) {
                                                      NSDictionary *dic = datas[0];
                                                      if ([dic isKindOfClass:[NSDictionary class]] &&
                                                          [dic objectForKey:@"ts"]) {
                                                          if (callBack) callBack(YES,[dic objectForKey:@"ts"]);
                                                          return;
                                                      }
                                                  }
                                                  else if ([datas isKindOfClass:[NSDictionary class]]&&
                                                           [datas objectForKey:@"ts"]){
                                                      if (callBack) callBack(YES,[dic objectForKey:@"ts"]);
                                                      return;
                                                  }
                                              }
                                          }
                                          LOError *loerror = MAKE_ERROR(@"请求服务器时间出错", -1000);
                                          if (callBack) callBack(NO,loerror);
                                      } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                          LOError *loerror = MAKE_ERROR(@"网路请求失败", JXErrorCodeTypeUnknown);
                                          if (callBack) callBack(NO,loerror);
                                      }];
    [operation resume];
}

- (void)netSocketServerAndPort:(NSString *)url callback:(void (^)(BOOL isSuccess,id object))callBack {
    if ([SocketManager shared].getserverAndPort &&
        [SocketManager shared].getserverAndPort.length) {
        NSString *url = [SocketManager shared].getserverAndPort;
        url = [NSString stringWithFormat:@"%@/1/server/get",url];
        NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:@{@"k":@"1",@"p":@"1"}];
        url = [self dicsToUrl:url params:newDic];
        
        NSURLSessionDataTask *operation = [JXRequestManager.sharedInstance GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (callBack) {
                callBack(YES ,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            LOError *loerror = MAKE_ERROR(error.localizedFailureReason, error.code);
            if (callBack) {
                callBack(NO ,loerror);
            }
        }];
        [operation resume];
    } else {
        NSDictionary *params = @{@"uid":JXRequestConfig.sharedManager.uid,
                                 @"app":@"potato"};
        NSDictionary *param = @{@"class":@"bottle",
                                @"method":@"ImServerList",
                                @"msgid":@(149),
                                @"params":params};
        weak_block_self;
        [self netBody:param result:^(BOOL isSuccess, id object) {
            if  (isSuccess) {
                [SocketManager shared].getserverAndPort = [[object objectForKey:@"result"] objectForKey:@"web"];
                if ([SocketManager shared].getserverAndPort && [SocketManager shared].getserverAndPort.length) {
                    NSString *url = [SocketManager shared].getserverAndPort;
                    url = [NSString stringWithFormat:@"%@/1/server/get",url];
                    NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:@{@"k":@"1",@"p":@"1"}];
                    url = [weakSelf dicsToUrl:url params:newDic];

                    NSURLSessionDataTask *operation = [JXRequestManager.sharedInstance GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        if (callBack) {
                            callBack(YES ,responseObject);
                        }
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        LOError *loerror = MAKE_ERROR(error.localizedFailureReason, error.code);
                        if (callBack) {
                            callBack(NO ,loerror);
                        }
                    }];
                    [operation resume];
                } else {
                    if (callBack) {
                        callBack(NO ,nil);
                    }
                }
            } else if (callBack) {
                callBack(NO ,nil);
            }
        }];
    }
    
}

- (void)netOffLineMsgWithUserA:(NSString *)userAID
                             userB:(NSString *)userBID
                            origin:(int)origin
                              size:(int)size
                             topic:(NSString *)topic
                          callBack:(void (^)(BOOL isSuccess,id object))callBack {
    if ([SocketManager shared].getserverAndPort &&
        [SocketManager shared].getserverAndPort.length) {
        NSString *url = [SocketManager shared].getserverAndPort;
        url = [NSString stringWithFormat:@"%@/1/msg/pairPage",[SocketManager shared].getserverAndPort];
        NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:@{@"a":userAID,@"b":userBID,
                                                                                      @"pageNo":@(origin),@"pageSize":@(size),@"topic":topic}];
        url = [self dicsToUrl:url params:newDic];

        NSURLSessionDataTask *operation = [JXRequestManager.sharedInstance GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (callBack) {
                callBack(YES ,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            LOError *loerror = MAKE_ERROR(error.localizedFailureReason, error.code);
            if (callBack) {
                callBack(NO ,loerror);
            }
        }];
        [operation resume];
    } else {
        NSDictionary *params = @{@"uid":JXRequestConfig.sharedManager.uid,
                                 @"app":@"nearby"};
        NSDictionary *param = @{@"class":@"bottle",
                                @"method":@"ImServerList",
                                @"msgid":@(149),
                                @"params":params};
        weak_block_self;
        [self netBody:param result:^(BOOL isSuccess, id object) {
            if  (isSuccess) {
                [SocketManager shared].getserverAndPort = [[object objectForKey:@"result"] objectForKey:@"web"];
                if ([SocketManager shared].getserverAndPort && [SocketManager shared].getserverAndPort.length) {
                    NSString *url = [NSString stringWithFormat:@"%@/1/msg/pairPage",[SocketManager shared].getserverAndPort];
                    NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:@{@"a":userAID,@"b":userBID,
                                                                                                  @"pageNo":@(origin),@"pageSize":@(size),@"topic":topic}];
                    url = [weakSelf dicsToUrl:url params:newDic];
                    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
                    [sessionManager.requestSerializer setTimeoutInterval:15];
                    sessionManager.responseSerializer.acceptableContentTypes=
                    [NSSet setWithObjects:@"application/json", @"text/json",@"text/javascript",@"text/html",@"text/plain",nil];
                    [sessionManager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
                    NSURLSessionDataTask *operation = [sessionManager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        if (callBack) {
                            callBack(YES ,responseObject);
                        }
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        LOError *loerror = MAKE_ERROR(error.localizedFailureReason, error.code);
                        if (callBack) {
                            callBack(NO ,loerror);
                        }
                    }];
                    [operation resume];
                } else {
                    if (callBack) {
                        callBack(NO ,nil);
                    }
                }
            }
        }];
    }
}

- (void)netOffLineMsg:(NSString *)uid many:(NSString *)many
                       callBack:(void (^)(BOOL isSuccess,id object))callBack {
    if ([SocketManager shared].getserverAndPort &&
        [SocketManager shared].getserverAndPort.length) {
        NSString *url = [SocketManager shared].getserverAndPort;
        url = [NSString stringWithFormat:@"%@/1/msg/status_many",url];
        NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:@{@"u":uid,@"many":many}];
        url = [self dicsToUrl:url params:newDic];
        AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
        [sessionManager.requestSerializer setTimeoutInterval:15];
        sessionManager.responseSerializer.acceptableContentTypes=
        [NSSet setWithObjects:@"application/json", @"text/json",@"text/javascript",@"text/html",@"text/plain",nil];
        [sessionManager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
        NSURLSessionDataTask *operation = [sessionManager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (callBack) {
                callBack(YES ,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            LOError *loerror = MAKE_ERROR(error.localizedFailureReason, error.code);
            if (callBack) {
                callBack(NO ,loerror);
            }
        }];
        [operation resume];
    } else {
        NSDictionary *params = @{@"uid":JXRequestConfig.sharedManager.uid,
                                 @"app":@"nearby"};
        NSDictionary *param = @{@"class":@"bottle",
                                @"method":@"ImServerList",
                                @"msgid":@(149),
                                @"params":params};
        weak_block_self;
        [self netBody:param result:^(BOOL isSuccess, id object) {
            if  (isSuccess) {
                [SocketManager shared].getserverAndPort = [[object objectForKey:@"result"] objectForKey:@"web"];
                if ([SocketManager shared].getserverAndPort && [SocketManager shared].getserverAndPort.length) {
                    NSString *url = [SocketManager shared].getserverAndPort;
                    url = [NSString stringWithFormat:@"%@/1/msg/status",url];
                    NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:@{@"u":uid}];
                    url = [weakSelf dicsToUrl:url params:newDic];
                    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
                    [sessionManager.requestSerializer setTimeoutInterval:15];
                    sessionManager.responseSerializer.acceptableContentTypes=
                    [NSSet setWithObjects:@"application/json", @"text/json",@"text/javascript",@"text/html",@"text/plain",nil];
                    [sessionManager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
                    NSURLSessionDataTask *operation = [sessionManager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        if (callBack) {
                            callBack(YES ,responseObject);
                        }
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        LOError *loerror = MAKE_ERROR(error.localizedFailureReason, error.code);
                        if (callBack) {
                            callBack(NO ,loerror);
                        }
                    }];
                    [operation resume];
                } else {
                    if (callBack) {
                        callBack(NO ,nil);
                    }
                }
            }
        }];
    }
    
}

- (id)checkIsSuccess:(NSDictionary *)dic{
    LOError *loerror = MAKE_ERROR(@"返回数据类型错误", 1000);
    if (![dic objectForKey:@"datas"]) return loerror;
    NSDictionary *datas = [dic objectForKey:@"datas"];
    if (![datas objectForKey:@"result"] || ![datas objectForKey:@"error"] )return loerror;
    NSDictionary *error = [datas objectForKey:@"error"];
    if ([[error objectForKey:@"code"] intValue] != 200){
        return MAKE_ERROR([error objectForKey:@"msg"], [[error objectForKey:@"code"] intValue]);
    }
    return nil;
}

- (id)init {
    self = [super init];
    if (self) {
        _reLock = [[NSLock alloc] init];
    }
    return self;
}

- (void)dealloc {
}
@end
